package com.las.bot.cmd.other;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.las.annotation.BotCmd;
import com.las.bot.common.Constant;
import com.las.cmd.BaseCommand;
import com.las.utils.mirai.CmdUtil;
import com.utils.DownFileUtils;
import com.utils.FileBase64Utils;
import com.utils.IdUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;

@BotCmd(funName = "AI绘画", isMatch = false)
public class MyAiPlainCmd extends BaseCommand {

    private static Logger logger = Logger.getLogger(MyAiPlainCmd.class);

    public MyAiPlainCmd() {
        super("绘画", "绘图","HT");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        String tags = command.substring(2);
        logger.info("AI绘图输入标签：" + tags);
        String api = "https://solutions-platinum-houston-another.trycloudflare.com/generate-stream";
        JSONObject object = new JSONObject();
        object.put("prompt", "masterpiece, best quality, " + tags);
        object.put("width", 512);
        object.put("height", 768);
        object.put("scale", 12);
        object.put("sampler", "k_euler_ancestral");
        object.put("steps", 28);
        object.put("seed", 1105461662);
        object.put("n_samples", 1);
        object.put("ucPreset", 0);
        object.put("uc", "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry");
        String result = HttpUtil.post(api, object.toJSONString());
        if (StrUtil.isNotBlank(result)) {
            String[] split = result.split("\\n");
            for (String sp : split) {
                if (sp.startsWith("data:")) {
                    String base64 = sp.split(":")[1].trim();
                    String fId = IdUtil.nextId();
                    File file = new File(fId + ".png");
                    String targetPath = file.getAbsolutePath();
                    FileBase64Utils.decodeBase64File(base64, targetPath);
                    String imgUrl = DownFileUtils.upFileAndDel(file, Constant.IMG_PNG);
                    logger.info("AI绘图响应结果：" + imgUrl);
                    ArrayList<String> list = new ArrayList<>();
                    list.add(imgUrl);
                    CmdUtil.sendImgMessage(list, userId, id, type);
                    break;
                }
            }
        }

    }


}
